"use strict";

function createVM(selector, data, func,watch) {
    var orgData = {
        PageShow: false //表单验证常用字段
        ,loading:false
        ,listLoading:false
        ,PageUrl:location.href
        ,root:baseUrl
        ,c1:color1
        ,c2:color2
        ,c3:color3
        ,
        rules: {
            notNull: {
                validate: function validate(val) {
                    return isTrue(val);
                    // return !!val;
                },
                message: '必填项'
            },
            min: function min(_min) {
                return {
                    validate: function validate(val) {
                        return val.length >= _min;
                    },
                    message: '字符长度不能小于' + _min
                };
            },
            max: function max(_max) {
                return {
                    validate: function validate(val) {
                        return val.length <= _max;
                    },
                    message: '字符长度不能大于' + _max
                };
            },
            len: function len(_len) {
                return {
                    validate: function validate(val) {
                        return val.length === _len;
                    },
                    message: '字符长度必须为' + _len
                };
            },
            isPhone: {
                validate: function validate(val) {
                    var myreg = /^[1][3,4,5,6,7,8][0-9]{9}$/;

                    if (!myreg.test(val)) {
                        return false;
                    } else {
                        return true;
                    }
                },
                message: '手机号不合法'
            },
            isNum: {
                validate: function validate(val) {
                    var myreg = /^([0-9\.])+?$/;

                    if (!myreg.test(val)) {
                        return false;
                    } else {
                        return true;
                    }
                },
                message: '请输入数字'
            }
        },
        PageRefreshing: false,
        PageHasLoadingMore: false,
        PageLoadingMore: false,
        picUserHead: picUserHead,
        picFilePath: picFilePath,
        picBanner: picBanner,
        picSBanner: picSBanner,
        picAdd: picAdd,
        pic404: pic404
        ,warning: {
            icon: 'priority_high',
            color: 'warning',
            message: "",
            open: false,
            timeout: 5000
        }
    };

    for (var i in data) {
        orgData[i] = data[i];
    }

    var methods = {};
    methods["initPage"] = function () {
        var header = document.querySelector('#statusbar');
        $api.fixStatusBar(header);
    };
    methods["goback"] = goback;
    methods["goto"] = goto;
    methods["gointo"] = gointo;
    methods["isFalse"] = isFalse;
    methods["isTrue"] = isTrue;
    methods["boole"] = isTrue;
    methods["inArray"] = isInArray;
    methods["showToast"] = showToast;
    methods["showWarning"] = showWarning;

    methods["OnLoad"] = function () {};
    methods["OnShow"] = function () {};
    methods["OnHide"] = function () {};
    methods["OnPullDownRefresh"] = function () {};
    methods["OnPullUpLoadMore"] = function () {}; //检查角色权限的方法


    methods["CanIUse"] = CanIUse; // methods["RoleWenYuan"]                 = RoleWenYuan;
    // methods["RoleFangLan"]                 = RoleFangLan;
    // methods["RoleRongJie"]                 = RoleRongJie;
    // methods["RoleZiGuan"]                  = RoleZiGuan;
    // methods["RoleJingLi"]                  = RoleJingLi;
    // methods["RoleAdmin"]                   = RoleAdmin;
    //常用的内置模板参数处理

    methods["getKm"] = getKm;
    methods["toFixed"] = function (num,len) {
        return num.toFixed(len)
    };
    methods["isPic"] = isPic;
    methods["download"] = download;
    methods["getDateTime"] = getDateTime;
    methods["getDate"] = getDate;
    methods["getTime"] = getTime;
    methods["getTimestamp"] = getTimestamp;
    methods["timeLeft"] = timeLeft;
    methods["timePass"] = timePass;
    methods["picRoot"] = getAssetBaseUrl;
    methods["picUrl"] = picUrl;
    methods["picBg"] = function (pic) {
        //创建随机背景色
        var rnd = Math.floor(Math.random()*10);//0-9
        var color = ["#ffd6d6","#ffead6","#fffed6","#eeffd6","#ddffd6","#d6ffef","#d6f1ff","#dbd6ff","#f8d6ff","#ffd6e3",]
        return "background-size: cover;background-color: "+ color[rnd] +";background-image: url('" + picUrl(pic) +"');"
    };
    methods["call"] = function (phone) {
        api.call({
            type: 'tel_prompt',
            number: phone
        });
    };
    methods["str2time"] = function (str) {
        var date = new Date(str);
        return getDateTime(date)
    };
    methods["hideNum"] = function (str) {
        function stripscript(s) {
            var pattern = new RegExp("[0-9A-Za-z一二三四五六七八九十壹贰叁肆伍陆柒捌玖拾]")
            var rs = "";
            for (var i = 0; i < s.length; i++) {
                rs = rs + s.substr(i, 1).replace(pattern, '*');
            }
            return rs;
        }
        return stripscript(str)
    };


    methods["scrollTo"] = function (item) {
        location.replace(this.PageUrl + "#" + item);
    };
    methods["scrollXTo"] = function (parent,son,index) {
        if (index < 0) {index = 0;}
        //计算总长度
        var scroll = 0 ;//300
        var sons = $api.domAll(son)
        for(var i in sons){
            if (i < index) {
                var offset = $api.offset( sons[i]);
                // logJson(offset)
                scroll += offset.w;
            }
        }
        //计算当前偏移
        var start =$api.dom(parent).scrollLeft;//100
        var line = scroll - start;//200
        var move = start
        var intervalIndex = setInterval(function () {
            line /= 2;
            move += line
            if (line * line < 4 ) {
                line = 0;
                clearInterval(intervalIndex)
            }
            $api.dom(parent).scrollLeft = move;
        },10)
    };
    for (var i in func) {
        methods[i] = func[i];
    }

    //数据监听
    var watches = {}
    if (isTrue(watch)){
        for (var i in watch) {
            watches[i] = watch[i];
        }
    }

    var vue = new Vue({
        el: selector,
        delimiters: ['[[', ']]'],
        data: orgData,
        //基础数据
        methods: methods,
        watch: watches
    });
    vue.initPage();
    return vue;
}

function isPic(path) {
    if (!isTrue(path)) {
        return false;
    }

    var suffix = get_suffix(path).toUpperCase().substring(1);
    log(suffix);

    if (suffix != "BMP" && suffix != "JPG" && suffix != "JPEG" && suffix != "PNG" && suffix != "GIF") {
        return false;
    } else {
        return true;
    }
}

function get_suffix(filename) {
    var pos = filename.lastIndexOf('.');
    var suffix = '';

    if (pos != -1) {
        suffix = filename.substring(pos);
    }

    return suffix;
}

function download(url, fileName) {
    if (!isTrue(url)) {
        showToast("文件丢失");
        return false;
    }

    showToast("开始下载");
    var path = "";

    if (fileName !== undefined) {
        path = "/storage/emulated/0/qzyt/" + fileName + get_suffix(url);
    } else {
        path = "/storage/emulated/0/qzyt/" + random_string() + get_suffix(url);
    }

    api.download({
        url: url,
        savePath: path
    }, function (ret, err) {
        if (ret.state == 1) {
            //下载成功
            showToast("下载成功");
        } else {}
    });
}
function GetDistances( lat1,  lng1,  lat2,  lng2){
    var radLat1 = lat1*Math.PI / 180.0;
    var radLat2 = lat2*Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var  b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
        Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
    s = s *6378.137 ;// EARTH_RADIUS;
    s = Math.round(s * 100) / 100;
    return s;
}

function getKm(lat1,lon1) {
    var lat = getLocData("lat")
    var lon = getLocData("lon")
    if (!isTrue(lat)) {
        return '受限';
    }
    return  GetDistances(lat,lon,lat1,lon1)
}